<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="24">
        <div style="margin-top:10px">
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addData" v-if="p1">新增</el-button>
          <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteAny" v-if="p4">删除</el-button>
        </div>
        <div class="query-form">
          <el-form ref="tableSearchParam" :model="tableSearchParam" label-width="50px" :inline="true">
            <el-form-item label="角色编码" label-width="70px">
              <el-input v-model="tableSearchParam.code" style="width:200px" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item label="角色名称" label-width="90px">
              <el-input v-model="tableSearchParam.name" style="width:200px" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="listTableData" icon="el-icon-search" size="small">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <br/>
        <el-table
          :data="tableData"
          border
          empty-text="暂无数据"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column
            label="角色编码"
            property="code"
            width="200">
          </el-table-column>
          <el-table-column
            label="角色名称"
            property="name"
            width="150">
          </el-table-column>
          <el-table-column
            property="createdTime"
            label="创建时间">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="success"
                v-if="p2"
                @click="editData(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-lemone-quanxianguanli"
                v-if="p3"
                @click="editPermission(scope.$index, scope.row)">权限分配
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-close"
                v-if="p4"
                @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes="[10, 20, 30, 40]"
            :page-size=this.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="actionType=='add'?'新增角色':'修改角色'" :visible.sync="dialogFormVisible" top="10vh">
      <el-form :model="formData" style="width:400px" :rules="rules" ref="ruleForm">
        <el-form-item label="角色编码" :label-width="formLabelWidth" prop="code">
          <el-input v-model="formData.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="formData.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="formData.description" auto-complete="off" :rows="6"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd" v-if="actionType=='add'" :loading="loading">保存</el-button>
        <el-button type="primary" @click="handleEdit" v-else :loading="loading">修改</el-button>
      </div>
    </el-dialog>
    <el-dialog title="权限分配" :visible.sync="dialogPermissionFormVisible" top="10vh" width="70%">
      <el-row :gutter="30">

        <el-col :span="8" style="border-right:1px solid #dcdfe6;">
          <div>
            <el-input
              placeholder="输入模块名称"
              size="small" style="margin-bottom:10px;margin-top:10px"
              @keyup.enter.native="searchTreeData"
              v-model="treeSearchInputValue"
              clearable>
            </el-input>
          </div>
          <div style="height:350px;overflow-y: auto">
            <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick" empty-text="暂无数据"
                     :default-expanded-keys="defaultExpandedKeys" :load="loadChildren" lazy highlight-current
                     node-key="id"></el-tree>
          </div>
        </el-col>
        <el-col :span="16">
          <div style="margin-top:10px;height:350px;overflow-y: auto">
            <el-checkbox-group style="margin-bottom: 10px" v-model="checkList">
              <div v-for="item in permissionData">
                <el-tag color="#2b85e4" style="color:white;margin-left:10px;margin-bottom:10px" size="large"
                >
                  <a @click.prevent="selectAllOpt(item.moduleId)">{{item.moduleName}}</a>
                </el-tag>
                <br/>
                <el-checkbox :style="index==0?'margin-left:15px':''" :label="item.id"
                             v-for="(item,index) in item.operationList" @change="operationCheckChange"
                             v-if="item.visiable=='1'">
                  {{item.name}}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPermissionFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlePermission" :loading="loading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
  .page {
    text-align: center;
    margin-top: 20px;
  }

  .query-form {
    border-bottom: 1px solid #ebeef5;
    padding-top: 25px;
  }

  .t-header {
    border: 1px solid #f2f2f2;
    background-color: #f8f8f8;
    height: 35px;
    font-size: 12px;
    font-weight: bold;
    line-height: 35px;
    padding-left: 32px
  }

  .t-body {
    margin-top: 10px;
    border: 1px solid #f2f2f2;
    background-color: #f8f8f8;
    font-size: 12px;
    padding-left: 12px
  }

  .el-checkbox + .el-checkbox {
    margin-left: 15px
  }

</style>

<script>
  import roleApi from '@/api/roleApi'
  import moduleApi from '@/api/moduleApi'
  import menuApi from '@/api/menuApi'
  import permissionApi from '@/api/permissionApi'

  export default {
    created() {
      this.p1 = this.permissionValid.validAction(this.permissionValid.permissionRule.role.addRole)
      this.p2 = this.permissionValid.validAction(this.permissionValid.permissionRule.role.updateRole)
      this.p3 = this.permissionValid.validAction(this.permissionValid.permissionRule.permission.savePermission)
      this.p4 = this.permissionValid.validAction(this.permissionValid.permissionRule.role.removeRole)
      this.initData()
    },
    data() {
      return {
        p1: false,
        p2: false,
        p3: false,
        p4: false,
        treeSearchInputValue: '',
        permissionData: [],
        defaultExpandedKeys: [],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label',
          isLeaf: 'leaf'
        },
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableSearchParam: {
          code: '',
          name: ''
        },
        dialogFormVisible: false,
        dialogPermissionFormVisible: false,
        formLabelWidth: '80px',
        formData: {
          code: '',
          name: '',
          description: ''

        },
        loading: false,
        actionType: '',
        multipleSelection: [],
        roleId: '',
        addPermissionData: {
          roleId: '',
          permissionList: []
        },
        checkList: [],
        rules: {
          code: [
            {required: true, message: '请输入角色编码', trigger: 'blur'},
            {max: 50, message: '长度不超过50 个字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入角色名称', trigger: 'blur'},
            {max: 50, message: '长度不超过50 个字符', trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      selectAllOpt(moduleId) {
        for (var pd of this.permissionData) {
          if (pd.moduleId == moduleId) {
            for (var o of pd.operationList) {
              var index = this.checkList.indexOf(o.id)
              if (index == -1) {
                this.checkList.push(o.id)
              }
            }
            break
          }
        }

        this.addOperationDataToPremission()
      },
      operationCheckChange(value) {
        if (value) {
          for (var pd of this.permissionData) {
            for (var o of pd.operationList) {
              var index = this.checkList.indexOf(o.id)
              if (index != -1) {
                //是否是新添加的操作
                if (pd.checkList.indexOf(this.checkList[index]) == -1) {
                  //添加关联操作id
                  if (o.relateOperation != null && o.relateOperation.length != 0) {
                    //遍历关联操作是否已经添加
                    for (var ro of o.relateOperation) {
                      if (this.checkList.indexOf(ro) == -1) {
                        this.checkList.push(ro)
                      }
                    }
                  }
                }
              }
            }
          }
          //添加对应的操作（针对permissionData里面的checkList）
          this.addOperationDataToPremission()
        } else {
          var cancel = ''
          console.log("####" + this.checkList)
          for (var pd of this.permissionData) {
            for (var o of pd.operationList) {
              var i = this.checkList.indexOf(o.id)
              if (i == -1) {
                //取消对应的操作（针对permissionData里面的checkList）
                var m = pd.checkList.indexOf(o.id)
                cancel = pd.checkList[m]
                if (m != -1) {
                  pd.checkList.splice(m, 1)
                }
                //取消关联操作
                if (o.relateOperation != null && o.relateOperation.length != 0) {
                  for (var ro of o.relateOperation) {
                    //取消对应的操作（全局的checkList）
                    var j = this.checkList.indexOf(ro)
                    if (j != -1 && this.a(ro)) {
                      this.checkList.splice(j, 1)
                    }
                  }
                }
              }
            }
            console.log("****" + this.checkList)
//            if (cancel != '') {
//              //取消与自己关联的操作
//              for (var pd of this.permissionData) {
//                for (var o of pd.operationList) {
//                  if (o.relateOperation != null && o.relateOperation.length != 0) {
//                    var n = o.relateOperation.indexOf(cancel)
//                    if (n != -1) {
//                      var p = this.checkList.indexOf(o.id)
//                      if (p != -1) {
//                        this.checkList.splice(p, 1)
//                      }
//                      var q = pd.checkList.indexOf(o.id)
//                      if (q != -1) {
//                        pd.checkList.splice(q, 1)
//                      }
//                    }
//                  }
//                }
//              }
//              //console.log("$$$$$" + this.checkList)
//            }
          }
        }
      },
      //判断操作是否被关联
      a(opt) {

        for (var pd of this.permissionData) {
          for (var o of pd.operationList) {
            if (o.relateOperation != null && o.relateOperation.length != 0) {
              var n = o.relateOperation.indexOf(opt)
              var m = this.checkList.indexOf(o.id)
              if (n != -1 && m != -1) {
                return false
              }
            }
          }
        }
        return true
      },
      addOperationDataToPremission() {
        for (var pd of this.permissionData) {
          for (var o of pd.operationList) {
            var index = this.checkList.indexOf(o.id)
            if (index != -1) {
              if (pd.checkList.indexOf(this.checkList[index]) == -1) {
                pd.checkList.push(this.checkList[index])
              }
            }
          }
        }
      },
      initData() {
        this.listTableData()
      },
      listTreeData() {
        menuApi.listAllMenu(this.treeSearchParam, (res) => {
          this.treeData = res
          for (var td of res) {
            this.defaultExpandedKeys.push(td.id)
          }
        }, () => {
        })
      },
      loadChildren(node, resolve) {
        if (node.level === 0) {
          return resolve(this.treeData)
        }
        this.treeSearchParam = {}
        this.treeSearchParam.menuId = node.data.id
        moduleApi.listAllModule(this.treeSearchParam, (res) => {
          resolve(res)
        }, () => {
        })
      },
      handleNodeClick(data) {
        permissionApi.listAllPermission({roleId: this.roleId, moduleId: data.id}, (res) => {
          this.permissionData = res
        }, () => {
        })
      },
      listTableData() {
        roleApi.listRole(this.tableSearchParam, this.currentPage, this.pageSize, (res) => {
          this.tableData = res.list
          this.total = res.total
        }, () => {
        })
      },
      addData() {
        //清空历史值
        this.formData = {
          code: '',
          name: '',
          description: ''

        }
        this.actionType = 'add'
        this.dialogFormVisible = true
        this.$refs['ruleForm'].resetFields()
      },
      handleAdd() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            roleApi.addRole(this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },
      editData(index, row) {
        //清空历史值
        this.formData = {
          code: '',
          name: '',
          description: ''

        }
        let that = this
        that.actionType = 'edit'
        this.loading = true
        roleApi.getRoleById(row.id, (res1) => {
          that.formData = res1
          that.formData.id = row.id
          this.loading = false
          that.dialogFormVisible = true
        }, () => {
        })
      },
      handleEdit() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            roleApi.updateRole(this.formData.id, this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })

      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          roleApi.deleteSingleRole(row.id, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      editPermission(index, row) {
        const loadings = this.$loading({
          lock: true,
          text: '拼命加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.roleId = row.id
        menuApi.listAllMenu(this.treeSearchParam, (res) => {
          this.treeData = res
          for (var td of res) {
            this.defaultExpandedKeys.push(td.id)
          }
          this.checkList = []
          permissionApi.listAllPermission({roleId: row.id}, (res) => {
            this.permissionData = res
            for (var pd of this.permissionData) {
              this.checkList = this.checkList.concat(pd.checkList)
            }
            this.dialogPermissionFormVisible = true
            loadings.close()
          }, () => {
            loadings.close()
          })
        }, () => {
        }, () => {
        })
//        moduleApi.listAllModule(this.treeSearchParam, (res) => {
//          this.treeData = res
//
//        })
      },
      handlePermission() {
        this.addPermissionData.roleId = this.roleId
        this.addPermissionData.permissionList = this.permissionData
        this.loading = true
        permissionApi.addPermission(this.addPermissionData, (res) => {
          this.loading = false
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.dialogFormVisible = false
        }, () => {
          this.loading = false
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.listTableData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.listTableData()
      },
      searchTreeData() {
        this.treeSearchParam = {}
        if (this.treeSearchInputValue == '') {
          this.treeSearchParam.name = ''
        } else {
          this.treeSearchParam.name = this.treeSearchInputValue
        }
        this.listTreeData()
      },
      handleSelectionChange(val) {
        this.multipleSelection = []
        for (var ms of val) {
          this.multipleSelection.push(ms.id)
        }
      },
      deleteAny() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return;
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          roleApi.deleteRole(this.multipleSelection, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>
